﻿using CKS2320.Common.Model;
using CKS2320.Common.Utils;
using CKS2320.Domain.DBEntity;
using CKS2320.Repository;
using CKS2320.Repository.Interface;
using CKS2320.Service.Interface;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CKS2320.Service
{
    public class VoltageWithstandService : IVoltageWithstandService
    {
        public IVoltageWithstandRepository _voltageWithstandRepository;
        private readonly LogService _logService;
        public VoltageWithstandService(IVoltageWithstandRepository voltageWithstandRepository, LogService logService)
        {
            _voltageWithstandRepository = voltageWithstandRepository;
            _logService = logService;
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <returns></returns>
        public List<IndicatorToleranceZoneModel> IndicatortolerancezoneJsonLoad()
        {
            string filePath = "Indicatortolerancezone.json";
            string text = File.ReadAllText(filePath);
            return JsonConvert.DeserializeObject<List<IndicatorToleranceZoneModel>>(text);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public ResultReturn Add(VoltageWithstandModel voltageWithstandModel)
        {
            try
            {
                List<IndicatorToleranceZoneModel> instance = IndicatortolerancezoneJsonLoad();
                //AC设定电压
                float? VoltageAc = null;
                //AC最终电流
                float? CurrentAc = null;
                //DC设定电压
                float? VoltageDc = null;
                //DC设定电流
                float? CurrentDc = null;
                //总长
                float? TotalLength = null;
                //大头垂直度
                float? BhVertical = null;
                //小头垂直度
                float? ShVertial = null;

                _logService.LogOp20("数据保存：" + JsonConvert.SerializeObject(voltageWithstandModel) + "\r\n");
                //if (voltageWithstandModel.VoltageWithstandResult == true)
                //    voltageWithstandModel.Result = true;
                //else
                //    voltageWithstandModel.Result = false;

                Voltagewithstand voltageWithstandEntity = new()
                {
                    Id = Guid.NewGuid(),
                    StationCode = voltageWithstandModel.StationCode,
                    Heart1 = voltageWithstandModel.Heart1,
                    StartUpLoad = voltageWithstandModel.StartUpLoad,
                    PartCode = voltageWithstandModel.PartCode,
                    Heart2 = voltageWithstandModel.Heart2,
                    EndUpLoad = voltageWithstandModel.EndUpLoad,
                    VoltageWithstandResult = voltageWithstandModel.VoltageWithstandResult,
                    VoltageWithstandResultAC = voltageWithstandModel.VoltageWithstandResultAC,
                    CameraDetectionResult = voltageWithstandModel.CameraDetectionResult,
                    TotalLengthResult = voltageWithstandModel.TotalLengthResult,
                    RunType = voltageWithstandModel.RunType,
                    Result = voltageWithstandModel.Result,
                    CreatedTime = DateTime.Now,
                    ModifiedTime = DateTime.Now
                };
                
                List<Detectiondetail> detailList = new();
                foreach (var item in voltageWithstandModel.detaillist)
                {
                    detailList.Add(new Detectiondetail()
                    {
                        Id = Guid.NewGuid(),
                        ParentId = voltageWithstandEntity.Id,
                        DetectedData = item.DetectedData,
                        DetectedType = item.DetectedType,
                        DetectedTypeDisplay = item.DetectedTypeDisplay,
                        Description = item.Description,
                        DetectedIndex = item.DetectedIndex,
                        DetectedStatus = item.DetectedStatus,
                        DetectedTime = item.DetectedTime,
                        PartCode = item.PartCode,
                        Plcip = item.Plcip,
                        CreatedTime = DateTime.Now,
                        ModifiedTime = DateTime.Now
                    });

                    VoltageAc = voltageWithstandModel.detaillist.Where(p => p.DetectedType == "ACv").FirstOrDefault()?.DetectedData;
                    CurrentAc = voltageWithstandModel.detaillist.Where(p => p.DetectedType == "ACa").FirstOrDefault()?.DetectedData;
                    VoltageDc = voltageWithstandModel.detaillist.Where(p => p.DetectedType == "DCv").FirstOrDefault()?.DetectedData;
                    CurrentDc = voltageWithstandModel.detaillist.Where(p => p.DetectedType == "DCa").FirstOrDefault()?.DetectedData;
                    TotalLength = voltageWithstandModel.detaillist.Where(p => p.DetectedType == "TL").FirstOrDefault()?.DetectedData;
                    BhVertical = voltageWithstandModel.detaillist.Where(p => p.DetectedType == "BHV").FirstOrDefault()?.DetectedData;
                    ShVertial = voltageWithstandModel.detaillist.Where(p => p.DetectedType == "SHV").FirstOrDefault()?.DetectedData;
                }

                IndicatorToleranceZoneModel? totalLengthIndicator = instance.FirstOrDefault(p => p.Content.Contains("TL"));
                //bool? totalLengthJudge = null;//总长判断
                //if (totalLengthIndicator.Indicator + totalLengthIndicator.ToleranceZone >= TotalLength && totalLengthIndicator.Indicator - totalLengthIndicator.ToleranceZone <= TotalLength)
                //{
                //    totalLengthJudge = true;
                //}
                //else
                //{
                //    totalLengthJudge = false;
                //}

                IndicatorToleranceZoneModel? bhvIndicator = instance.FirstOrDefault(p => p.Content.Contains("BHV"));
                bool? bhvJudge = null;//大端判断
                if (bhvIndicator.Indicator + bhvIndicator.ToleranceZone >= BhVertical && bhvIndicator.Indicator - bhvIndicator.ToleranceZone <= BhVertical)
                {
                    bhvJudge = true;
                }
                else
                {
                    bhvJudge = false;
                }

                IndicatorToleranceZoneModel? shvIndicator = instance.FirstOrDefault(p => p.Content.Contains("SHV"));
                bool? shvJudge = null;//小端判断
                if (shvIndicator.Indicator + shvIndicator.ToleranceZone >= ShVertial && shvIndicator.Indicator - shvIndicator.ToleranceZone <= ShVertial)
                {
                    shvJudge = true;
                }
                else
                {
                    shvJudge = false;
                }

                Op20coredata op20CoreData = new Op20coredata()
                {
                    SerialNumber = voltageWithstandModel.PartCode,
                    Passageway = voltageWithstandModel.RunType,
                    TestTime = DateTime.Now,
                    VoltageAc = VoltageAc,
                    CurrentAc = CurrentAc,
                    ResultAc = voltageWithstandModel.VoltageWithstandResultAC == true ? "OK" : "NG",
                    ResultDc = voltageWithstandModel.VoltageWithstandResult == true ? "OK" : "NG",
                    VoltageDc = VoltageDc,
                    CurrentDc = CurrentDc,
                    TotalLength = TotalLength,
                    TotalLengthJudge = voltageWithstandModel.TotalLengthResult==true?"OK":"NG",//totalLengthJudge == true ? "OK" : "NG",
                    BhVerticality = BhVertical,
                    BhVerticalityJudge = bhvJudge == true ? "OK" : "NG",
                    ShVerticality = ShVertial,
                    ShVerticalityJudge = shvJudge == true ? "OK" : "NG",
                    ShVerticalityTotalJudge = "OK",//这是什么判断？？
                    finalJudge = voltageWithstandModel.Result == true ? "OK" : "NG"
                };
                _logService.LogOp20("客户核心数据保存：" + JsonConvert.SerializeObject(op20CoreData) + "\r\n");
                return _voltageWithstandRepository.Add(voltageWithstandEntity, detailList, op20CoreData);
            }
            catch (Exception ex)
            {
                _logService.LogOp20("保存失败：" + ex.ToString(), LogLevel.Error);
                return MessageInfoUtils.Fail(ex.Message);
            }
        }

    }
}
